package la.bbs558.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author: WeiHanmin
 * @description: Spring容器工具类
 * @time: 2021-09-18 13:49:55
 */
@Component
public class ApplicationUtils{
    @Resource
    private ApplicationContext applicationContextX;

    private static ApplicationContext applicationContext;

    @PostConstruct
    public void init(){
        applicationContext = applicationContextX;
    }

    public static Object getBean(String s) throws BeansException {
        return applicationContext.getBean(s);
    }
    
    public static <T> T getBean(Class<T> aClass) throws BeansException {
        return applicationContext.getBean(aClass);
    }

    //已经new出来的对象进行注入
    public static <T> T autowire(T bean){
        applicationContext.getAutowireCapableBeanFactory()
                .autowireBeanProperties(bean, AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, true);
        return bean;
    }

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }
}
